import axios from "axios";
import config from "./config";
import { getSession } from "./storage";

class Request {
  baseURL;
  timeout;
  constructor() {
    this.baseURL = config.interfaceBase;
    this.timeout = 15000;
  }

  getToken = () => {
    return `Bearer ${getSession("access_token")}`;
  };

  mergeOptions(options = {}) {
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options,
    };
  }

  setInterceptors(instance) {
    instance.interceptors.request.use(
      (config) => {
        config.headers = {
          Authorization: this.getToken(),
          post: {
            "Content-Type": "application/json;charset=UTF-8",
          },
        };
        return config;
      },
      (err) => Promise.reject(err)
    );

    instance.interceptors.response.use(
      (response) => response.data,
      (err) => Promise.reject(err)
    );
  }

  request(options = {}) {
    const instance = axios.create();
    const opts = this.mergeOptions(options);
    this.setInterceptors(instance);
    return instance(opts);
  }

  get(url, config = {}) {
    return this.request({
      url,
      method: "GET",
      ...config,
    });
  }

  post(url, data) {
    return this.request({
      url,
      method: "POST",
      data,
    });
  }
}

export default Request;
